package com.dukla.picbak.handler;

import com.drew.imaging.FileType;
import com.drew.imaging.FileTypeDetector;
import com.drew.imaging.avi.AviMetadataReader;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.mp4.Mp4MetadataReader;
import com.drew.imaging.tiff.TiffMetadataReader;
import com.drew.metadata.Metadata;
import com.drew.metadata.avi.AviDirectory;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.mp4.Mp4Directory;
import com.dukla.picbak.vo.MediaFileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.*;
import java.nio.file.Files;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

@Component
public class FileScanner {

    private final Logger logger =
            LoggerFactory.getLogger(FileScanner.class);

    @Value("${pic-backup.na-log-file}")
    String naLogFileName;

    @Autowired
    DataContainer dataContainer;

    public void start(){
        File naLogFile = new File(naLogFileName);
        try {
            BufferedReader br = new BufferedReader(new FileReader(naLogFile));
            String line;
            while ((line = br.readLine()) != null){
                String[] fields = line.split(",");
                //第2列为文件路径
                String path = fields[1];
                logger.info("Process N/A file:{}",path);
                this.process(new File(path));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    private void process(File file){
        try {
            FileType fileType = FileTypeDetector.detectFileType(new BufferedInputStream(Files.newInputStream(file.toPath())));
            //元数据
            Metadata meta;
            //媒体日期
            Date mediaDate;
            switch (fileType){
                case Jpeg:
                    meta = JpegMetadataReader.readMetadata(file);
                    mediaDate = getExifDate(meta);
                    break;
                case Mp4:
                    meta=Mp4MetadataReader.readMetadata(file);
                    mediaDate = getMp4Date(meta);
                    break;
                case Avi:
                    meta=AviMetadataReader.readMetadata(file);
                    mediaDate = getAviDate(meta);
                    break;
                default:
                    logger.info("{}-file:{},passed!",fileType.getName(),file.getName());
                    return;
            }
            if(mediaDate==null){
                logger.warn("MediaDate is null,set to default dir!");
            }
            //推送入库队列
            MediaFileInfo fileInfo=new MediaFileInfo();
            fileInfo.setFile(file);
            fileInfo.setMediaDate(mediaDate);
            this.dataContainer.putFileContentQueue(fileInfo);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }

    }

    private Date getMp4Date(Metadata meta){
        //获取MP4目录
        Collection<Mp4Directory> dirs = meta.getDirectoriesOfType(Mp4Directory.class);
        Date date = null;
        if(ObjectUtils.isEmpty(dirs)){
            return date;
        }
        for(Mp4Directory dir:dirs){
            //获取创建日期
            date = dir.getDate(Mp4Directory.TAG_CREATION_TIME);
            if (date != null) {
                return date;
            }
            //获取修改日期
            date = dir.getDate(Mp4Directory.TAG_MODIFICATION_TIME);
            if (date != null) {
                return date;
            }
        }
        return date;
    }

    private Date getAviDate(Metadata meta){
        //获取Avi目录
        Collection<AviDirectory> dirs = meta.getDirectoriesOfType(AviDirectory.class);
        Date date = null;
        if(ObjectUtils.isEmpty(dirs)){
            return date;
        }
        for(AviDirectory dir:dirs){
            //获取创建日期
            date = dir.getDate(AviDirectory.TAG_DATETIME_ORIGINAL);
            if (date != null) {
                return date;
            }
        }
        return date;
    }

    private Date getExifDate(Metadata meta){
        //获取Exif目录
        Collection<ExifSubIFDDirectory> dirs = meta.getDirectoriesOfType(ExifSubIFDDirectory.class);
        Date date = null;
        if(ObjectUtils.isEmpty(dirs)){
            return date;
        }
        for (ExifSubIFDDirectory dir:dirs){
            //获取创建日期
            date = dir.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
            if (date != null) {
                return date;
            }
            //获取修改日期
            date = dir.getDate(ExifSubIFDDirectory.TAG_DATETIME);
            if (date != null) {
                return date;
            }
        }
        return date;
    }
}
